package vn.com.vega.chacha.v2.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.PlayerScreen;
import vn.com.vega.chacha.v2.Asynctask.DoSomthingListener;
import vn.com.vega.chacha.v2.Asynctask.FavoriteSong;
import vn.com.vega.chacha.v2.player.PlayerService;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.downloadmanager.DownloadUtil;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.utils.AnimationChaCha;
import vn.com.vega.music.utils.PlaylistUtil;
import vn.com.vega.music.utils.Util;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class PlayerViewThumbFragment extends Fragment implements
		OnClickListener, OnSeekBarChangeListener {
	private PlayerScreen mPlayerAct;
	private Appinstant mApp;
	private LinearLayout mLaytoutTopMenu;
	private ImageView mThumb;
	private TextView mSongTitle;
	private ImageButton mAddToPlaylistBtn;
	private ImageButton mDownloadBtn;
	private SeekBar mVoloumeControl;
	private AudioManager mAm;
	private ImageButton mMuteBtn, mMaxVolumeBtn, mMenuAddPlaylistBtn,
			mMenuDownloadbtn, mMenuLikeBtn, mMenuRingtoneBtn, mMenuShareBtn;
	private DataStore mdataStore;
	private Toast mToast;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.player_thumb_view, null);
		mLaytoutTopMenu = (LinearLayout) view
				.findViewById(R.id.layout_player_topmenu);
		mThumb = (ImageView) view.findViewById(R.id.imv_song_thumb);
		mSongTitle = (TextView) view.findViewById(R.id.tv_song_title_in_player);
		mAddToPlaylistBtn = (ImageButton) view
				.findViewById(R.id.bt_addd_to_playllist);
		mDownloadBtn = (ImageButton) view.findViewById(R.id.bt_download_song);
		mVoloumeControl = (SeekBar) view
				.findViewById(R.id.seekbar_volume_control);

		mAddToPlaylistBtn.setOnClickListener(this);
		mDownloadBtn.setOnClickListener(this);
		mThumb.setOnClickListener(this);
		mVoloumeControl.setOnSeekBarChangeListener(this);

		mMuteBtn = (ImageButton) view.findViewById(R.id.bt_mute);
		mMaxVolumeBtn = (ImageButton) view.findViewById(R.id.bt_max_volum);
		mMenuAddPlaylistBtn = (ImageButton) view
				.findViewById(R.id.bt_menu_add_to_playlist);
		mMenuDownloadbtn = (ImageButton) view
				.findViewById(R.id.bt_menu_download_song);
		mMenuLikeBtn = (ImageButton) view.findViewById(R.id.bt_menu_like_song);
		mMenuRingtoneBtn = (ImageButton) view
				.findViewById(R.id.bt_menu_ringtone);
		mMenuShareBtn = (ImageButton) view.findViewById(R.id.bt_menu_share);
		mMaxVolumeBtn.setOnClickListener(this);
		mMuteBtn.setOnClickListener(this);
		mMenuAddPlaylistBtn.setOnClickListener(this);
		mMenuDownloadbtn.setOnClickListener(this);
		mMenuLikeBtn.setOnClickListener(this);
		mMenuRingtoneBtn.setOnClickListener(this);
		mMenuShareBtn.setOnClickListener(this);

		mdataStore = DataStore.getInstance();

		return view;
	}

	private void showToast(String msg) {
		if (mToast == null) {
			mToast = Toast.makeText(getActivity(), "", Toast.LENGTH_LONG);
		}
		mToast.setText(msg);
		mToast.show();
	}

	private static final int HIDE_MENU = 100;
	private static final int TIME_AUTO_HIDE = 4000;
	private ThumbHandler handler = new ThumbHandler(this);

	static class ThumbHandler extends Handler {
		WeakReference<PlayerViewThumbFragment> playerThumbViewRfc;

		public ThumbHandler(PlayerViewThumbFragment thumbFragment) {
			// TODO Auto-generated constructor stub
			playerThumbViewRfc = new WeakReference<PlayerViewThumbFragment>(
					thumbFragment);
		}

		private boolean checkIsLive() {
			PlayerViewThumbFragment thumbFragment = playerThumbViewRfc.get();
			if (thumbFragment == null) {
				return false;
			}
			if (thumbFragment.mPlayerAct == null
					|| thumbFragment.mPlayerAct.isDestroy) {
				return false;
			}
			return true;
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (!checkIsLive()) {
				// Remove all message and call back
				removeCallbacksAndMessages(null);
				return;
			}
			PlayerViewThumbFragment thumbFragment = playerThumbViewRfc.get();
			switch (msg.what) {
			case HIDE_MENU:
				thumbFragment.showTopMenu(false);
				break;

			default:
				break;
			}

		}

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mPlayerAct = (PlayerScreen) getActivity();
		mApp = (Appinstant) mPlayerAct.getApplication();
		updateInfo();
	}

	public void updateInfo() {
		Song songCurrent = Util.getCurrentSongPlay();
		if (songCurrent == null) {
			return;
		}
		mSongTitle.setText(songCurrent.title);
		mApp.mImageLoader.download(songCurrent.imageUrl, mThumb);
		mAm = (AudioManager) mPlayerAct.getSystemService(Context.AUDIO_SERVICE);
		int currentVolume = mAm.getStreamVolume(AudioManager.STREAM_MUSIC);
		int max = mAm.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mVoloumeControl.setMax(max);
		mVoloumeControl.setProgress(currentVolume);
		
		if (songCurrent.isLocalSong()) {
			mMenuAddPlaylistBtn.setVisibility(View.GONE);
			mMenuDownloadbtn.setVisibility(View.GONE);
			mMenuLikeBtn.setVisibility(View.GONE);
			mMenuShareBtn.setVisibility(View.GONE);
			mDownloadBtn.setVisibility(View.GONE);
			mAddToPlaylistBtn.setVisibility(View.GONE);
		} else {
			mMenuAddPlaylistBtn.setVisibility(View.VISIBLE);
			mMenuDownloadbtn.setVisibility(View.VISIBLE);
			mMenuLikeBtn.setVisibility(View.VISIBLE);
			mMenuShareBtn.setVisibility(View.VISIBLE);
			mDownloadBtn.setVisibility(View.VISIBLE);
			mAddToPlaylistBtn.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Song song = Util.getCurrentSongPlay();
		if (song == null) {
			// DO nothing
			return;
		}
		switch (v.getId()) {
		case R.id.imv_song_thumb:
			if (mLaytoutTopMenu.isShown()) {
				showTopMenu(false);
			} else {
				showTopMenu(true);
			}
			break;
		case R.id.bt_mute:
			showTopMenu(false);
			mAm.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 1);
			break;
		case R.id.bt_max_volum:
			showTopMenu(false);
			mAm.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 1);
			break;
		case R.id.bt_addd_to_playllist:
		case R.id.bt_menu_add_to_playlist:
			showTopMenu(false);
			if (!mPlayerAct.checkIsConnect()) {
				return;
			}
			addSongToPlaylist(song);
			break;
		case R.id.bt_download_song:
		case R.id.bt_menu_download_song:
			showTopMenu(false);
			if (!mPlayerAct.checkIsConnect()) {
				return;
			}
			downloadSong(song);
			break;

		case R.id.bt_menu_like_song:
			showTopMenu(false);
			if (!mPlayerAct.checkIsConnect()) {
				return;
			}
			likeSong(song);
			break;
		case R.id.bt_menu_ringtone:
			showTopMenu(false);
			if (!mPlayerAct.checkIsConnect()) {
				return;
			}
			listRingtoneOfSong(song);
			break;
		case R.id.bt_menu_share:
			showTopMenu(false);
			shareSong(song);
			break;

		default:
			break;
		}
	}

	private void addSongToPlaylist(Song song) {
		List<Song> listSong = new ArrayList<Song>();
		listSong.add(song);
		PlaylistUtil.addSongToPlaylist(listSong, mPlayerAct);
	}

	private void downloadSong(Song song) {
//		if (mdataStore.songIsDownloaded(song)) {
//			showToast("Bài hát đã được tải về");
//			return;
//		}
		if (DownloadUtil.checkSongIsInListDownload(song)) {
			showToast("Bài hát đã được thêm vào danh sách tải về");
			return;
		}
		DownloadUtil.downloadSong(song, mPlayerAct);
	}

	DoSomthingListener doLikeSongListener = new DoSomthingListener() {

		@Override
		public void startDoSomthing(List<Object> extractObject) {
			// TODO Auto-generated method stub
			String message = (String) extractObject.get(0);
			showToast(message);
		}

		@Override
		public void doSomethingSuccess(List<Object> extractObject) {
			// TODO Auto-generated method stub
			String message = (String) extractObject.get(1);
			if (!Util.checkStringIsemptyOrNull(message)) {
				showToast(message);
			}
		}

		@Override
		public void doSomethingFail(List<Object> extractObject) {
			// TODO Auto-generated method stub
			String errorMessage = (String) extractObject.get(1);
			if (!Util.checkStringIsemptyOrNull(errorMessage)) {
				showToast(errorMessage);
			}
		}
	};

	private void likeSong(Song song) {
//		Playlist favPlaylist = mdataStore
//				.getSpecialPlaylistByType(Playlist.TYPE_FAVORITE);
//		if (favPlaylist == null) {
//			showToast("không thành công");
//		} else {
			FavoriteSong favoriteSong;
			if (song.isFavorite) {
				favoriteSong = new FavoriteSong(mPlayerAct, song, doLikeSongListener, false);
			} else {
				favoriteSong = new FavoriteSong(mPlayerAct, song, doLikeSongListener, true);
			}
			favoriteSong.execute();
//		}
	}

	private void listRingtoneOfSong(Song song) {
		Appinstant app = (Appinstant) mPlayerAct.getApplication();
		app.showListRingtone(mPlayerAct, song.title);
	}

	private void shareSong(Song song) {
		Util.share(song.shareMessage, mPlayerAct);
	}

	private void showTopMenu(boolean show) {
		if (show) {
			Song currentPlay = Util.getCurrentSongPlay();
//			if (mdataStore.songIsDownloaded(currentPlay)) {
//				mMenuDownloadbtn.setVisibility(View.GONE);
//			} else {
//				mMenuDownloadbtn.setVisibility(View.VISIBLE);
//			}
			if (currentPlay.isFavorite) {
				mMenuLikeBtn.setSelected(true);
			} else {
				mMenuLikeBtn.setSelected(false);
			}
			
			int currentVolume = mAm.getStreamVolume(AudioManager.STREAM_MUSIC);
			mVoloumeControl.setProgress(currentVolume);
			mLaytoutTopMenu.startAnimation(AnimationChaCha.infFromTop(200));
			mLaytoutTopMenu.setVisibility(View.VISIBLE);
			handler.sendEmptyMessageDelayed(HIDE_MENU, TIME_AUTO_HIDE);
		} else {
			mLaytoutTopMenu.startAnimation(AnimationChaCha.outToTop(200));
			mLaytoutTopMenu.setVisibility(View.GONE);
			handler.removeMessages(HIDE_MENU);
		}
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		if (fromUser) {
			mAm.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 1);
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		handler.removeMessages(HIDE_MENU);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		handler.sendEmptyMessageDelayed(HIDE_MENU, TIME_AUTO_HIDE);
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (PlayerService.PLAYSTATE_CHANGED.equalsIgnoreCase(action)) {
				updateInfo();
			}
		}
	};

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mPlayerAct.unregisterReceiver(receiver);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(PlayerService.PLAYSTATE_CHANGED);
		mPlayerAct.registerReceiver(receiver, intentFilter);
	}

}
